package com.netty.client;

import io.netty.bootstrap.Bootstrap;
import io.netty.channel.Channel;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.util.Attribute;

import java.util.concurrent.ConcurrentHashMap;

import com.netty.ServerAddress;
import com.netty.channel.ChannelAttribute;

/**
 * netty.client连接管理
 * 
 * @author zhoufang
 *
 *         2017年12月23日下午11:25:24
 */
public class ClientNettyManager {

	/**
	 * key: 目标服务器serverId value: 连接数据
	 */
	private static ConcurrentHashMap<Integer, ClientNettyConnect> clientConnects = new ConcurrentHashMap<Integer, ClientNettyConnect>();

	private static Bootstrap bootstrap = null;
	private static EventLoopGroup loopGroup = null;

	public static void init(int threadNumber) {
		bootstrap = new Bootstrap();
		loopGroup = new NioEventLoopGroup(threadNumber);
		bootstrap.group(loopGroup);
		bootstrap.channel(NioSocketChannel.class);
		bootstrap.handler(new ClientChannelInitializer());
	}

	/**
	 * 连接服务器
	 * 
	 * @param serverAddress
	 *            服务器地址
	 */
	public synchronized static void connectServer(ServerAddress serverAddress) {
		if (clientConnects.containsKey(serverAddress.getServerId())) {
			return;
		}
		ClientNettyConnect clientConnect = new ClientNettyConnect(serverAddress);
		clientConnects.put(serverAddress.getServerId(), clientConnect);
		clientConnect.connect();
	}

	public static Bootstrap getBootstrap() {
		return bootstrap;
	}

	public static void channelInactive(Channel channel) {
		Attribute<Integer> attr = channel.attr(ChannelAttribute.SS_CLIENT_ID);
		ClientNettyConnect nettyConnect = clientConnects.get(attr.get());
		nettyConnect.reConnect(channel);
	}

}
